import urllib.request
import os

def url_open(url):
    req = urllib.request.Request(url)
    req.add_header('User_Agent','Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36')
    response = urllib.request.urlopen(url)
    html = response.read()
    return html

def get_page(url):  #查找页面
    html = url_open(url).decode('utf-8')
    #<span class="current-comment-page">[166]</span>
    a = html.find('current-comment-page')+23 #23：current-comment-page">[
    b = html.find(']',a)

    #print(html[a:b])  
    return html[a:b] #【获得页码】 如166

def find_imgs(url): #查找图片地址
    html = url_open(url).decode('utf-8')
    img_addrs = []
    #<img src="//wx4.sinaimg.cn/mw600/781e975fgy1fh96nnwp0qj20rg0iftao.jpg" style="max-width: 480px; max-height: none;">
    
    c = html.find('img src=')
    
    while c != -1:#当可以找到‘img src=’时
        d = html.find('.jpg',c,c+255)
        if d != -1: #如果找到了‘.jpg’
            img_addrs.append('http:'+ html[c+9:d+4])#9:img src=",4:.jpg
        else:
            d = c + 9
            
        c = html.find('img src=',d)

    #print(img_addrs)    
    return img_addrs #【获得图片地址】如http://wx4.sinaimg.cn/mw600/781e975fgy1fh96nnwp0qj20rg0iftao.jpg

def save_imgs(folder,img_addrs):#保存图片
    for each in img_addrs:
        filename = each.split('/')[-1]#摘取文件名
        with open(filename,'wb') as f:
            img = url_open(each)
            f.write(img)

def download_mm(folder = 'TP',pages = 10):
    os.mkdir(folder)
    os.chdir(folder)
    
    url = "http://jandan.net/ooxx/"
    page_num = int(get_page(url))#查找页面
    
    for i in range(pages):#在每页中查找图片
        page_num -= i
        page_url = url + 'page-' + str(page_num) + '#comments'
        #页面网址：http://jandan.net/ooxx/page-166#comments
        img_addrs = find_imgs(page_url) #查找图片地址
        save_imgs(folder,img_addrs)     #保存
        
if __name__ == '__main__':
    download_mm()
